//
//  YYLUserAccount.swift
//  XinlangWeibo
//
//  Created by yangyinglei on 2017/3/29.
//  Copyright © 2017年 yangyinglei. All rights reserved.
//

import UIKit

//    let userAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!).appending("userAccount.achiver")
   let userAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.achiver")

//用户账号模型
class YYLUserAccount: NSObject, NSCoding {

    
    //  令牌
    var access_token: String?
    //  access_token的生命周期  单位是秒 获取到access_token的过期时间
    var expires_in: Int = 0{
        didSet{
        //  获取当前的时间+过期秒数 = expiresDate
        expiresDate = Date().addingTimeInterval(TimeInterval(expires_in))
        
        }
    }
    //根据过期描述计算过期时间对象
    var expiresDate: Date?
    
    //  用户的唯一标识符
    var uid: Int64 = 0
    //  用户昵称
    var name: String?
    //  用户头像地址
    var avatar_large: String?
    //kvc构造函数
    init(dic: [String: Any]) {
        super.init()
        setValuesForKeys(dic)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        //空实现
    }
    
    //MARK:------归档解解档的代理
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token =  aDecoder.decodeObject(forKey: "access_token") as! String?
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as! Date?
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as! String?
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as! String?
    }
    //把用户信息保存到本地   归档
    func saveUserAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: userAccountPath)
    }
    //获取本地用户对象
    class func loadUserAccount ()->YYLUserAccount? {
        let obj = NSKeyedUnarchiver.unarchiveObject(withFile: userAccountPath)
        
        return obj as? YYLUserAccount
    }
    
}
